package com.lot.test;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;

import java.util.Random;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;

public class NettyHandler extends ChannelInboundHandlerAdapter {
    ExecutorService executor = Executors.newCachedThreadPool();
    private Random random = new Random();
    private long time1;
    private long time2;
    private static AtomicInteger SENT_COUNT = new AtomicInteger(0);
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        // super.channelActive(ctx);
        executor.execute(()->{
            while (true){
                try {
                    Thread.sleep(10);
                }catch (Exception e){

                }

                if (SENT_COUNT.get()==0){
                    time1 = System.currentTimeMillis();
                }
                if (SENT_COUNT.get()==10000){
                    System.out.println("用时："+(System.currentTimeMillis()-time1)/1000);
                    executor.shutdownNow();
                    return;
                }
                StringBuilder stringBuilder = new StringBuilder();
                stringBuilder.append("1234#").append(random.nextFloat()).append("#")
                        .append(random.nextFloat()).append("#").append(SENT_COUNT.getAndIncrement());
                System.out.println(stringBuilder.toString());
                ByteBuf byteBuf = Unpooled.copiedBuffer(stringBuilder.toString(),CharsetUtil.UTF_8);
                ctx.writeAndFlush(byteBuf);
                System.out.println(SENT_COUNT.get());
            }

        });
    }
}
